﻿using System;
using System.Diagnostics;

namespace Gonte.Web.Json
{
    /// <summary>
    /// Encapsulates the response from a form
    /// </summary>
    public class JsonFormResponse
    {
        #region Constructors

        static JsonFormResponse()
        {
            TraceSource = new TraceSource("Gonte.Web.TraceSource");
        }

        public JsonFormResponse()
        {
            success = true;
        } 

        #endregion

        #region Properties

        /// <summary>
        /// Whether the operation succeeded or not
        /// </summary>
        public bool success { get; set; }

        /// <summary>
        /// The message when the operation succeeded or error when operation failed
        /// </summary>
        public string msg { get; set; }

        /// <summary>
        /// Data to be passed to the client
        /// </summary>
        public object data { get; set; }

        /// <summary>
        /// The trace source to log
        /// </summary>
        public static TraceSource TraceSource { get; set; } 

        #endregion

        #region Methods

        /// <summary>
        /// Processes a form
        /// </summary>
        /// <param name="action">Action to be executed</param>
        /// <returns>Result to be returned in JSON format</returns>
        public void Process(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                success = false;
                msg = ex.Message;

                TraceSource.TraceEvent(TraceEventType.Error, 0, "{0} {1}", ex.Message, ex.StackTrace);
            }
        } 

        #endregion
    }
}
